﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 
    /// </summary>
    public class PortalService : DataFactory, PortalIService
    {
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PortalEntity>> GetList(PageInput input)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<PortalEntity>();
                var queryParams = input.queryJson.ToObject();
                //关键字（名称、编码）
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    queryWhere = queryWhere.And(m => m.FullName.Contains(input.keyword) || m.EnCode.Contains(input.keyword));
                }
                return await db.GetIQueryable<PortalEntity>().Where(queryWhere).OrderBy(t => t.SortCode).GetPageResultAsync(input);
            }
        }

        /// <summary>
        /// 获取功能信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<PortalEntity> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<PortalEntity>(m => m.Id == id);
            }
        }

        /// <summary>
        /// 创建新功能信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(PortalEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(PortalEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(entity);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task<int> Delete(PortalEntity entity)
        {
            using (var db = this.Basic)
            {
                await db.DeleteAsync<AuthorizeEntity>(m => m.ItemId == entity.Id);
                return await db.DeleteAsync(entity);
            }
        }

        public async Task<List<PortalEntity>> GetList()
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<PortalEntity>().OrderBy(o => o.SortCode).ToListAsync();
            }
        }
    }
}
